package io.bluerain.bocket.io;

import io.bluerain.bocket.callback.ReceiverHandler;
import io.bluerain.bocket.message.ByteMessage;
import io.bluerain.bocket.message.Message;
import io.bluerain.bocket.message.TextMessage;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class SocketIo {

    protected Socket client;
    protected Socket server;
    protected Charset charset;
    protected BufferedReader br;
    protected PrintStream out;
    protected OutputStream outputStream;
    protected InputStream inputStream;
    protected DataInputStream dataInputStream;
    protected DataOutputStream dataOutputStream;

    public void out(Message message) {
        if (message instanceof TextMessage) {
            out.println(message.getText());
        } else if (message instanceof ByteMessage) {
            try {
                if (dataOutputStream == null)
                    dataOutputStream = new DataOutputStream(outputStream);
                dataOutputStream.write(message.getData());
                dataOutputStream.flush();
            } catch (IOException e) {
                System.out.println("log - 发送字节流失败");
                e.printStackTrace();
            }
        }
    }

    public void outSystemIn() {
        br = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        try {
            while ((line = br.readLine()) != null && !line.trim().equals("exit")) {
                out(new TextMessage(line));
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            if (client != null)
                client.close();
            if (server != null)
                server.close();
            if (br != null)
                br.close();
            if (out != null)
                out.close();
            if (inputStream != null)
                inputStream.close();
            if (outputStream != null)
                outputStream.close();
            if (dataInputStream != null)
                dataInputStream.close();
            if (dataOutputStream != null)
                dataOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SubIo connect(String addr, int port, Charset charset, ReceiverHandler receiverHandler) {
        SubIo io = new SubIo(addr, port, charset, receiverHandler);
        return io;
    }

    public static SubIo connect(String addr, int port, ReceiverHandler receiverHandler) {
        return connect(addr, port, StandardCharsets.UTF_8, receiverHandler);

    }

    public static SubIo connect(String addr, ReceiverHandler receiverHandler) {
        return connect(addr, 80, receiverHandler);
    }

    public Socket getClient() {
        return client;
    }
}
